<!-- 用户编辑弹窗 -->
<template>
  <a-modal
    :width="450"
    :visible="visible"
    :confirm-loading="loading"
    :title="isUpdate ? '修改用户' : '新建用户'"
    :body-style="{ paddingBottom: '8px' }"
    @update:visible="updateVisible"
    @ok="save"
  >
    <a-form
      ref="form"
      :model="form"
      :rules="rules"
      :label-col="{ md: { span: 7 }, sm: { span: 24 } }"
      :wrapper-col="{ md: { span: 17 }, sm: { span: 24 } }"
    >
      <a-row :gutter="8">
        <a-col :md="20" :sm="24" :xs="24">
          <a-form-item label="账号:" name="account">
            <a-input v-model:value="form.account" placeholder="请输入账号" allow-clear autocomplete="off" />
          </a-form-item>
          <a-form-item label="姓名:" name="realName">
            <a-input v-model:value="form.realName" placeholder="请输入姓名" allow-clear />
          </a-form-item>
          <a-form-item label="手机号:" name="phone">
            <a-input v-model:value="form.phone" placeholder="请输入手机号" maxlength="11" allow-clear />
          </a-form-item>
          <a-form-item v-if="!isUpdate" label="登录密码:" name="password">
            <a-input-password v-model:value="form.password" placeholder="密码8-16位数字、字母或符号组成" autocomplete="new-password" />
          </a-form-item>
          <a-form-item v-if="!isUpdate" label="确认密码:" name="repeatPassword">
            <a-input-password v-model:value="form.repeatPassword" placeholder="密码8-16位数字、字母或符号组成" autocomplete="off" />
          </a-form-item>

          <a-form-item label="角色" name="roleId">
            <a-radio-group default-value="1339550467939639304" v-model:value="form.roleId" button-style="solid">
              <a-radio-button value="1339550467939639304">BMSH管理者</a-radio-button>
              <a-radio-button value="1339550467939639305">BMSH营业者</a-radio-button>
            </a-radio-group>
          </a-form-item>

          <a-form-item label="负责地域:" name="region" v-if="form.roleId === '1339550467939639305'">
            <a-select size="medium"
                      mode="multiple"
                      placeholder="负责地域"
                      v-model:value="form.region"
                      style="width: 240px;"
                      :required="true">
              <a-select-option v-for="region in regionList" :key="region" :value="region">
                {{ region }}
              </a-select-option>
            </a-select>
          </a-form-item>
<!--          <a-form-item label="机构:" name="orgId">
            <a-tree-select
              v-model:value="form.orgId"
              style="width: 100%"
              :tree-data="orgList"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              placeholder="请选择上级机构"
              :replaceFields="{ children: 'children', title: 'title', key: 'id', value: 'id' }"
              allow-clear
              tree-default-expand-all
            >
            </a-tree-select>
          </a-form-item>-->
<!--          <a-form-item label="职位:" name="positionId">
            <a-select
              show-search
              v-model:value="form.positionId"
              placeholder="请选择职务"
              style="width: 100%"
              :show-arrow="false"
              :filter-option="false"
              :not-found-content="null"
              allow-clear
            >
              <a-select-option v-for="item in positionList" :key="item.positionId">
                {{ item.positionName }}
              </a-select-option>
            </a-select>
          </a-form-item>-->


<!--          <a-form-item label="邮箱:" name="email" v-if="isUpdate">
            <a-input v-model:value="form.email" placeholder="请输入邮箱" allow-clear />
          </a-form-item>-->
        </a-col>
<!--        <a-col :md="12" :sm="24" :xs="24">
          <a-form-item label="昵称:" name="nickName">
            <a-input v-model:value="form.nickName" placeholder="请输入昵称" allow-clear />
          </a-form-item>
          <a-form-item label="性别:" name="sex">
            <a-select v-model:value="form.sex" placeholder="请选择性别" allow-clear>
              <a-select-option value="M">男</a-select-option>
              <a-select-option value="F">女</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="出生日期:" name="birthday">
            <a-date-picker v-model:value="form.birthday" value-format="YYYY-MM-DD" placeholder="请选择出生日期" class="ele-fluid" />
          </a-form-item>
          <a-form-item label="邮箱:" name="email" v-if="!isUpdate">
            <a-input v-model:value="form.email" placeholder="请输入邮箱" allow-clear autocomplete="off" />
          </a-form-item>
        </a-col>-->
      </a-row>
    </a-form>
  </a-modal>
</template>

<script>
import validate from 'ele-admin-pro/packages/validate';
import { UserApi } from '@/api/UserApi';
import { onMounted, ref } from 'vue';
import { AgentApi } from '@/api/AgentApi';

export default {
  name: 'UserEdit',
  emits: ['done', 'update:visible'],
  props: {
    // 弹窗是否打开
    visible: Boolean,
    // 修改回显的数据
    data: Object,
    // 组织机构列表
    orgList: Array
  },

  setup() {
    // 加载代理商下拉数据
    const regionList = ref([]);
    async function fetchRegionList() {
      const res = await AgentApi.findRegionList({});
      regionList.value = res.data;
    }
    // 页面初次挂载时加载下拉数据
    onMounted(async () => {
      await fetchRegionList();
    });
    return {
      regionList
    };
  },

  data() {
    return {
      // 表单数据
      form: Object.assign({}, this.data),
      // 表单验证规则
      rules: {
        realName:[{ required: true, message: '请输入姓名', type: 'string', trigger: 'blur' }],
        account: [{ required: true, message: '请输入用户账号', type: 'string', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', type: 'string', trigger: 'blur' }],
        repeatPassword: [
          { required: true, message: '请输入重复密码', type: 'string', trigger: 'blur' },
          {
            type: 'string',
            trigger: 'blur',
            // eslint-disable-next-line no-unused-vars
            validator: async (rule, value, callback) => {
              const password = this.form.password;
              if (value && password !== value) {
                return Promise.reject('两次密码输入不一致');
              } else {
                return Promise.resolve();
              }
            }
          }
        ],
        /*email: [{ pattern: validate.email, message: '邮箱格式不正确', type: 'string', trigger: 'blur' }],*/
        /*orgId: [{ required: true, message: '请选择组织机构', trigger: 'blur' }],*/
        phone: [{ required: true, pattern: validate.phone, message: '手机号格式不正确', type: 'string', trigger: 'blur' }],
        //region: [{ required: true, message: '请选择地域', trigger: 'blur' }],
        region: [{ required: true, message: '请选择负责地域', trigger: 'change',
          validator: (rule, value, callback) => {
            console.log(this.form.region);
            if(this.form.region && this.form.region.length > 0){
              callback();
            }else{
              callback(new Error('负责地域不能为空'));
            }
          }}],
      },
      // 提交状态
      loading: false,
      // 是否是修改
      isUpdate: false,
      // 角色列表
      roleList: [],
      // 职位列表
      positionList: []
    };
  },
  watch: {
    visible(){
      if (!this.data) {
        // 新增-清除表格内容
        this.form = {};
        this.form.roleId = '1339550467939639304';// 默认值
      } else {
        this.form = Object.assign({}, this.data);
      }
      // 清空表单校验信息
      if (this.$refs.form) {
        this.$refs.form.clearValidate();
      }
    },
    data() {
      if (this.data) {
        // 编辑的时候适配组件数据类型
        if (typeof this.data.region === 'string') {
          if (this.data.region === '') {
            this.data.region = [];
          } else {
            this.data.region = this.data.region.split(','); // 假设你想根据逗号分割
          }
        }

        this.form = Object.assign({}, this.data);
        this.isUpdate = true;
      } else {
        this.form = {
          roleId : '1339550467939639304'// 默认值
        };
        this.isUpdate = false;
      }
      if (this.$refs.form) {
        this.$refs.form.clearValidate();
      }
    }
  },
  async mounted() {
    // 获取职位列表
    this.positionList = await UserApi.getPositionDropList();
  },
  methods: {
    /**
     * 保存和编辑用户
     *
     * @author fengshuonan
     * @date 2021/4/7 11:00
     */
    async save() {
      // 校验表单
      await this.$refs.form.validate();

      // 校验账号只能录入  数字、字母、符号
      const reg = /^[a-zA-Z0-9._-]*$/;
      if (this.form.account && !reg.test(this.form.account)) {
        this.$message.error('账号只能输入数字、字母和 . _ -');
        this.loading = false;
        return;
      }

      if (!this.isUpdate) {
        // 校验密码是8-16位数字、字母或符号组合
        const simplePasswordRegex = /^[a-zA-Z0-9!@#$%^&*(),.?":{}|<>]{8,16}$/;
        if (this.form.password && !simplePasswordRegex.test(this.form.password)) {
          this.$message.error('密码必须为8-16位数字、字母或符号组合');
          this.loading = false;
          return;
        }
        // 校验一个字符串不能是纯数字
        const notPureNumberRegex = /^(?!\d+$).*$/;
        if (this.form.password && !notPureNumberRegex.test(this.form.password)) {
          this.$message.error('密码必须为8-16位数字、字母或符号组合(当前纯数字)');
          this.loading = false;
          return;
        }
        // 校验一个字符串不能是纯字母
        const notPureLetterRegex = /^(?!^[a-zA-Z]+$).*/;
        if (this.form.password && !notPureLetterRegex.test(this.form.password)) {
          this.$message.error('密码必须为8-16位数字、字母或符号组合（当前纯字母）');
          this.loading = false;
          return;
        }
        // 校验一个字符串不能是纯字母
        const notPureSymbolRegex = /^(?![!@#$%^&*(),.?":{}|<>]+$).*$/;
        if (this.form.password && !notPureSymbolRegex.test(this.form.password)) {
          this.$message.error('密码必须为8-16位数字、字母或符号组合（当前纯符号）');
          this.loading = false;
          return;
        }
      }

      // 修改加载框为正在加载
      this.loading = true;

      let result;

      // 设置地区
      if (this.form.region) {
        this.form.region = this.form.region.join(',');
      }

      // 执行编辑或修改用户方法
      if (this.isUpdate) {
        result = UserApi.editUser(this.form);
      } else {
        result = UserApi.addUser(this.form);
      }
      result
        .then(result => {
          // 移除加载框
          this.loading = false;

          // 提示添加成功
          this.$message.success(result.message);

          // 如果是新增用户，则form表单置空
          if (!this.isUpdate) {
            this.form = {};
          }

          // 关闭弹框，通过控制visible的值，传递给父组件
          this.updateVisible(false);

          // 触发父组件done事件
          this.$emit('done');
        })
        .catch(() => {
          this.loading = false;
        });
    },

    /**
     * 更新编辑用户界面的弹框是否显示
     *
     * @param value true-显示，false-隐藏
     * @author fengshuonan
     * @date 2021/4/7 11:00
     */
    updateVisible(value) {
      this.$emit('update:visible', value);
    }
  }
};
</script>

<style scoped></style>
